package com.jpatest.demo.configuration;

import com.jpatest.demo.Redis.MyRedisChannelListener;
import com.jpatest.demo.Redis.TwoLevelCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.time.Duration;

@Configuration
@AutoConfigureAfter(RedisConfiguration.class)
public class CacheConfiguration {
    @Autowired
    private MessageListenerAdapter adapter;

    @Bean
    public TwoLevelCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, RedisTemplate redisTemplate){
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration.entryTtl(Duration.ofSeconds(30));
        TwoLevelCacheManager redisCacheManager = new TwoLevelCacheManager(redisTemplate, redisCacheWriter, redisCacheConfiguration);
        MyRedisChannelListener listener = (MyRedisChannelListener) adapter.getDelegate();
        listener.setCacheManager(redisCacheManager);
        return redisCacheManager;
    }
}
